package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Channel;
import com.example.springboot.entity.Comment;
import com.example.springboot.service.IChannelService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/channel")
public class ChannelController {

    @Resource
    private IChannelService channelService;

    //查询所有数据
    @GetMapping()
    public Result findAll() {
        return Result.success(channelService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(channelService.getById(id));
    }


    //新增和修改
    @PostMapping
    public Result save(@RequestBody Channel channel) {  //@RequestBody接收前端数据
        //新增或者更新
        return Result.success(channelService.saveOrUpdate(channel));
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(channelService.removeById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {

        return Result.success(channelService.removeByIds(ids));
    }

    //分页查询Mybatis-plus的方式,模糊查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") Integer id,
                           @RequestParam(defaultValue = "") String channel,
                           @RequestParam(defaultValue = "") String title) {

        QueryWrapper<Channel> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (id != null) {
            queryWrapper.eq("id", id);
        }
        if (!"".equals(channel)) {
            queryWrapper.eq("channel", channel);
        }
        if (!"".equals(title)) {
            queryWrapper.like("title", title);
        }
        return Result.success(channelService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}
